package main

import (
	"embed"
	"io/fs"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
	"gopkg.in/mgo.v2"
)

//go:embed pages/dist/*
var embedFs embed.FS

func init() {
	var err error
	Session, err = mgo.Dial("mongodb://root:root@127.0.0.1:27017")
	if err != nil {
		log.Fatal("mongodb,", err)
	}
	log.Print("mongodb connect Success.")
}
func HttpServer() *gin.Engine {
	e := gin.Default()
	fpages, _ := fs.Sub(embedFs, "pages")
	fdist, _ := fs.Sub(fpages, "dist")
	fjs, _ := fs.Sub(fdist, "js")
	fcss, _ := fs.Sub(fdist, "css")
	e.StaticFS("/js", http.FS(fjs))
	e.StaticFS("/css", http.FS(fcss))

	user := e.Group("/user")
	device := e.Group("/device")
	user.POST("/query", func(c *gin.Context) {
		result := []bson.M{}
		collection := Session.DB("remote").C("user")
		item := bson.M{"email": c.PostForm("email")}
		err := collection.Find(item).One(&result)
		if err == nil {
			c.JSON(http.StatusOK, gin.H{"msg": "", "data": result})
		} else {
			c.JSON(http.StatusOK, gin.H{"msg": err.Error(), "data": result})
		}
	})
	user.POST("/add", func(c *gin.Context) {
		collection := Session.DB("project").C("user")
		err := collection.Insert(bson.M{
			"name":     c.PostForm("name"),
			"password": c.PostForm("password"),
			"email":    c.PostForm("email"),
		})
		if err == nil {
			c.JSON(http.StatusOK, gin.H{"msg": "", "data": nil})
		} else {
			c.JSON(http.StatusOK, gin.H{"msg": err.Error(), "data": nil})
		}
	})
	device.POST("/query", func(c *gin.Context) {
		result := []bson.M{}
		collection := Session.DB("remote").C("device")
		item := bson.M{"email": c.PostForm("email")}
		err := collection.Find(item).One(&result)
		if err == nil {
			c.JSON(http.StatusOK, gin.H{"msg": "", "data": result})
		} else {
			c.JSON(http.StatusOK, gin.H{"msg": err.Error(), "data": result})
		}
	})
	device.POST("/add", func(c *gin.Context) {
		collection := Session.DB("project").C("device")
		err := collection.Insert(bson.M{
			"cpuid":    c.PostForm("cpuid"),
			"code":     c.PostForm("code"),
			"password": c.PostForm("password"),
			"email":    c.PostForm("email"),
		})
		if err == nil {
			c.JSON(http.StatusOK, gin.H{"msg": "", "data": nil})
		} else {
			c.JSON(http.StatusOK, gin.H{"msg": err.Error(), "data": nil})
		}
	})
	user.POST("/email", func(c *gin.Context) {

	})
	user.POST("/verify", func(c *gin.Context) {

	})
	return e
}
